#coding:UTF-8
import os

import sys 
from PyQt4.QtCore import * 
from PyQt4.QtGui import * 
import urllib

from ui_staticmap import Ui_Dialog

google_key='ABQIAAAAj5cpJ2swzFT77RVZXuP73BRi_j0U6kJrkFvY4-OX2XYmEAa76BQmXyAoEUqQGRkT8yJX9ACbfqQXsA'

def main(): 
    app = QApplication(sys.argv) 
    w = MyWindow() 
    w.show() 
    sys.exit(app.exec_()) 
     
class MyWindow(QDialog): 
    def __init__(self, *args): 
        QDialog.__init__(self, *args) 
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)

        # create connection
        self.connect(self.ui.pushButton, SIGNAL("clicked()"), self.run_command)
     #  self.connect(self.ui.le, SIGNAL("returnPressed(void)"), self.run_command)

    def getGeoCode(self, addr):
        geo_url='http://maps.google.com/maps/geo?'+urllib.urlencode({'q':addr})+'&output=csv&key='+google_key
        try:
           g=urllib.urlopen(geo_url)
           ret=g.read().split(',')
           
           if(ret[0]!='200'):
      	      QMessageBox.warning(None, "Error", addr+" not found", QMessageBox.Yes)
           else:
      	      self.showMap(ret[2], ret[3]) 
      	           
        except urllib.HTTPError:
           QMessageBox.warning(None, "Error", "Http error", QMessageBox.Yes)

    def showMap(self, lat,lang):
        stmap_url='http://maps.google.com/staticmap?center='+lat+','+lang+'&markers='+lat+','+lang+',red&zoom=14&size=512x512&maptype=mobile&key='+google_key
        print stmap_url
        urllib.urlretrieve(stmap_url, "stmap.gif")
        image = QImage("stmap.gif")
        self.ui.imageLabel.setPixmap(QPixmap.fromImage(image))
        self.ui.imageLabel.adjustSize()

    def run_command(self):
        addr = str(self.ui.le.text().toUtf8())
        self.getGeoCode(addr)
  
if __name__ == "__main__": 
    main() 
